#include "responsivetest.h"
#include "customfilelistwidget.h"
#include "customfilebrowser.h"
#include <QApplication>
#include <QElapsedTimer>
#include <QRandomGenerator>

ResponsiveTest::ResponsiveTest(QObject* parent)
    : QObject(parent)
    , m_factory(nullptr)
    , m_performanceMonitor(nullptr)
    , m_testWidget(nullptr)
    , m_testEngine(nullptr)
{
    m_factory = &ResponsiveFactory::instance();
    m_performanceMonitor = &PerformanceMonitor();

    m_testTimer = new QTimer(this);
    m_testTimer->setSingleShot(true);
    m_testTimer->setInterval(TEST_TIMEOUT_MS);
    connect(m_testTimer, &QTimer::timeout, this, &ResponsiveTest::onTestTimeout);

    // 连接性能监控信号
    connect(m_performanceMonitor, &SonyPerformanceMonitor::performanceWarning,
            this, &ResponsiveTest::onPerformanceWarning);
    connect(m_performanceMonitor, &SonyPerformanceMonitor::optimizationSuggested,
            this, &ResponsiveTest::onOptimizationSuggested);

}

void ResponsiveTest::runAllTests()
{

    m_passedTests.clear();
    m_failedTests.clear();
    m_totalTests = 0;
    m_passedCount = 0;
    m_failedCount = 0;

    // 启动超时计时器
    m_testTimer->start();

    // 运行各类测试
    runComponentTests();
    runPerformanceTests();
    runIntegrationTests();

    // 生成测试报告
    QString summary = getTestSummary();

    m_testTimer->stop();

    if (allTestsPassed()) {
    } else {
    }

}

void ResponsiveTest::runComponentTests()
{

    logTestResult("ResponsiveFactory", testResponsiveFactory());
    logTestResult("ResponsiveFileListEngine", testResponsiveFileListEngine());
    logTestResult("ResponsiveFileItem", testResponsiveFileItem());
    logTestResult("AdaptiveFileLayout", testAdaptiveFileLayout());
    logTestResult("PerformanceMonitor", testPerformanceMonitor());
    logTestResult("SonyDesignIntegration", testSonyDesignIntegration());
    logTestResult("ConfigurationSystem", testConfigurationSystem());
}

void ResponsiveTest::runPerformanceTests()
{

    m_performanceMonitor->startMonitoring();

    logTestResult("MemoryManagement", testMemoryManagement());
    logTestResult("AnimationSystem", testAnimationSystem());
    logTestResult("CachePerformance", testCachePerformance());

    measurePerformanceMetrics();

    m_performanceMonitor->stopMonitoring();
}

void ResponsiveTest::runIntegrationTests()
{

    setupTestData();
    simulateUserInteractions();
    cleanupTestData();
}

bool ResponsiveTest::allTestsPassed() const
{
    return m_failedCount == 0 && m_totalTests > 0;
}

QStringList ResponsiveTest::getFailedTests() const
{
    return m_failedTests;
}

QString ResponsiveTest::getTestSummary() const
{
    return QString("测试总结: 总计 %1 个测试，通过 %2 个，失败 %3 个")
           .arg(m_totalTests)
           .arg(m_passedCount)
           .arg(m_failedCount);
}

void ResponsiveTest::onPerformanceWarning(const QString& warning)
{
}

void ResponsiveTest::onOptimizationSuggested(const QString& suggestion)
{
}

void ResponsiveTest::onTestTimeout()
{
}

bool ResponsiveTest::testResponsiveFactory()
{
    try {
        // 测试单例模式
        ResponsiveFactory& factory1 = ResponsiveFactory::instance();
        ResponsiveFactory& factory2 = ResponsiveFactory::instance();
        if (&factory1 != &factory2) {
            return false;
        }

        // 测试组件创建
        auto* engine = m_factory->createResponsiveEngine(this);
        if (!engine) {
            return false;
        }

        auto* layout = m_factory->createAdaptiveFileLayout(this);
        if (!layout) {
            return false;
        }

        // 测试配置应用
        m_factory->applySonyDesignDefaults(engine);
        m_factory->applyPerformanceOptimizations(engine);

        delete engine;
        delete layout;

        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testResponsiveFileListEngine()
{
    try {
        auto* engine = m_factory->createResponsiveEngine(this);

        // 测试显示模式计算
        SonyIveDesign::DisplayMode mode1 = engine->calculateDisplayMode(150);
        if (mode1 != SonyIveDesign::DisplayMode::Micro) {
            return false;
        }

        SonyIveDesign::DisplayMode mode2 = engine->calculateDisplayMode(300);
        if (mode2 != SonyIveDesign::DisplayMode::Standard) {
            return false;
        }

        // 测试模式阈值设置
        engine->setModeThreshold(SonyIveDesign::DisplayMode::Compact, 200);
        // 需要验证设置是否生效

        delete engine;
        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testResponsiveFileItem()
{
    try {
        UnifiedFileInfo fileInfo;
        fileInfo.fileName = "test_file.pdf";
        fileInfo.fileType = FileType::PDF;
        fileInfo.pageCount = 100;

        auto* engine = m_factory->createResponsiveEngine(this);
        auto* item = m_factory->createResponsiveFileItem(fileInfo, engine, nullptr);

        if (!item) {
            return false;
        }

        // 测试基本功能
        item->setSelected(true);
        if (!item->isSelected()) {
            return false;
        }

        item->setHovered(true);
        if (!item->isHovered()) {
            return false;
        }

        // 测试显示模式切换
        item->setDisplayMode(SonyIveDesign::DisplayMode::Full);
        if (item->getDisplayMode() != SonyIveDesign::DisplayMode::Full) {
            return false;
        }

        delete engine;
        delete item;
        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testAdaptiveFileLayout()
{
    try {
        auto* layout = m_factory->createAdaptiveFileLayout(this);

        // 测试基本布局计算
        QSize itemSize = layout->calculateItemSize(SonyIveDesign::DisplayMode::Standard, 800);
        if (itemSize.width() <= 0 || itemSize.height() <= 0) {
            return false;
        }

        // 测试列数计算
        int columns = layout->calculateOptimalColumns(800, itemSize.width());
        if (columns <= 0) {
            return false;
        }

        delete layout;
        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testPerformanceMonitor()
{
    try {
        SonyPerformanceMonitor monitor;

        // 测试监控功能
        monitor.startMonitoring();
        if (!monitor.isAutoOptimizationEnabled()) {
            monitor.enableAutoOptimization(true);
        }

        // 模拟一些帧
        for (int i = 0; i < 10; ++i) {
            monitor.beginFrame();
            QThread::msleep(1);
            monitor.endFrame();
        }

        double fps = monitor.getCurrentFPS();
        if (fps <= 0) {
            return false;
        }

        // 测试缓存监控
        monitor.recordCacheHit("test");
        monitor.recordCacheMiss("test");
        int hitRate = monitor.getCacheHitRate("test");
        if (hitRate < 0 || hitRate > 100) {
            return false;
        }

        monitor.stopMonitoring();
        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testSonyDesignIntegration()
{
    try {
        // 测试Sony设计配置
        if (ResponsiveConfig::SonyDesign::MICRO_MODE_THRESHOLD <= 0) {
            return false;
        }

        if (ResponsiveConfig::SonyDesign::HOVER_SCALE_FACTOR <= 1.0) {
            return false;
        }

        // 测试颜色配置
        if (ResponsiveConfig::SonyDesign::Colors::ACCENT_BLUE_R < 0 ||
            ResponsiveConfig::SonyDesign::Colors::ACCENT_BLUE_R > 255) {
            return false;
        }

        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testConfigurationSystem()
{
    try {
        ResponsiveFactory& factory = ResponsiveFactory::instance();

        // 测试全局配置
        factory.setGlobalResponsiveMode(true);
        if (!factory.isGlobalResponsiveModeEnabled()) {
            return false;
        }

        factory.setAnimationEnabled(false);
        if (factory.isAnimationEnabled()) {
            return false;
        }

        factory.setAnimationEnabled(true);
        if (!factory.isAnimationEnabled()) {
            return false;
        }

        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testMemoryManagement()
{
    try {
        // 创建大量组件测试内存管理
        QList<ResponsiveFileItem*> items;
        UnifiedFileInfo fileInfo;
        fileInfo.fileName = "test_memory.pdf";
        fileInfo.fileType = FileType::PDF;

        auto* engine = m_factory->createResponsiveEngine(this);

        for (int i = 0; i < 1000; ++i) {
            auto* item = m_factory->createResponsiveFileItem(fileInfo, engine, nullptr);
            items.append(item);
        }

        // 清理内存
        for (auto* item : items) {
            delete item;
        }
        items.clear();

        delete engine;
        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testAnimationSystem()
{
    try {
        // 测试动画配置
        if (ResponsiveConfig::SonyDesign::ANIMATION_DURATION <= 0) {
            return false;
        }

        if (ResponsiveConfig::Performance::ANIMATION_THROTTLE_DELAY <= 0) {
            return false;
        }

        return true;
    } catch (...) {
        return false;
    }
}

bool ResponsiveTest::testCachePerformance()
{
    try {
        SonyPerformanceMonitor monitor;
        monitor.startMonitoring();

        // 模拟大量缓存操作
        for (int i = 0; i < 10000; ++i) {
            if (i % 3 == 0) {
                monitor.recordCacheHit("performance_test");
            } else {
                monitor.recordCacheMiss("performance_test");
            }
        }

        int hitRate = monitor.getCacheHitRate("performance_test");
        if (hitRate < 0 || hitRate > 100) {
            return false;
        }

        monitor.stopMonitoring();
        return true;
    } catch (...) {
        return false;
    }
}

void ResponsiveTest::setupTestData()
{

    // 创建测试文件信息
    m_testFiles.clear();
    for (int i = 0; i < TEST_FILE_COUNT; ++i) {
        UnifiedFileInfo fileInfo;
        fileInfo.fileName = QString("test_file_%1.pdf").arg(i);
        fileInfo.filePath = QString("/test/path/test_file_%1.pdf").arg(i);
        fileInfo.fileType = (i % 3 == 0) ? FileType::PDF : FileType::Image;
        fileInfo.pageCount = QRandomGenerator::global()->bounded(1, 200);
        fileInfo.fileSize = QRandomGenerator::global()->bounded(1024, 1024 * 1024);
        m_testFiles.append(fileInfo);
    }

    // 创建测试组件
    m_testEngine = m_factory->createResponsiveEngine(this);
    // 注意：实际使用中需要有效的parent和browser
}

void ResponsiveTest::cleanupTestData()
{

    if (m_testEngine) {
        delete m_testEngine;
        m_testEngine = nullptr;
    }

    if (m_testWidget) {
        delete m_testWidget;
        m_testWidget = nullptr;
    }

    m_testFiles.clear();
}

void ResponsiveTest::logTestResult(const QString& testName, bool passed, const QString& details)
{
    m_totalTests++;
    if (passed) {
        m_passedCount++;
        m_passedTests.append(testName);
    } else {
        m_failedCount++;
        m_failedTests.append(testName);
        if (!details.isEmpty()) {
        }
    }
}

void ResponsiveTest::simulateUserInteractions()
{

    // 模拟窗口大小变化
    for (int width = 100; width <= 1000; width += 100) {
        if (m_testEngine) {
            SonyIveDesign::DisplayMode mode = m_testEngine->calculateDisplayMode(width);
            // 验证模式切换是否正常
        }
    }

    // 模拟文件选择
    for (int i = 0; i < 10; ++i) {
        // 模拟选择操作
    }
}

void ResponsiveTest::measurePerformanceMetrics()
{

    QElapsedTimer timer;
    timer.start();

    // 执行性能敏感操作
    for (int i = 0; i < 1000; ++i) {
        SonyIveDesign::DisplayMode mode = m_testEngine->calculateDisplayMode(i * 2);
        Q_UNUSED(mode)
    }

    qint64 elapsed = timer.elapsed();

    if (elapsed > 1000) { // 1秒阈值
    }
}